﻿
#include "SettingsHelper.h"

#include <QDebug>
#include <QTextCodec>

#define APPNAME "GWZD"
static const char *SettingFileName =  "conf.ini";


static const char *DebuggerFileName = "debugger.ini";
static const char *BaseDirName = "gwzd_tunner";

SettingsHelper::SettingsHelper(QObject *parent)
    : QObject{parent}
    , _appName(tr(APPNAME))
{
    init_();
}

void SettingsHelper::init_()
{
    mtx_.lock();
    QDir rootDir(BaseDirName);
    if (!rootDir.exists()) {
        QDir().mkpath(BaseDirName);
    }
    _rootDir = rootDir;

    QString filePath = rootDir.filePath(SettingFileName);
    QFile file(filePath);
    if(!file.exists()) {
        createDefaultSettings_(filePath);
    }
    settings_ = new QSettings(filePath, QSettings::IniFormat);
    QString debuggerPath = rootDir.filePath(DebuggerFileName);
    QFile debuggerFile(debuggerPath);
    if(!debuggerFile.exists()) {
       createGrounedSettings_(debuggerPath);
    }
    groundedSettings_ = new QSettings(debuggerPath,QSettings::IniFormat);
    mtx_.unlock();
    getDebuggerList();
}

void SettingsHelper::createDefaultSettings_  (const QString &filePath)
{
    QSettings defaultSettings(filePath,QSettings::IniFormat);
    defaultSettings.setValue("NavigateViewMode",0);
    defaultSettings.setValue("DarkMode",0);
    defaultSettings.setValue("Language","zh_CN");
    defaultSettings.sync();
}

void  SettingsHelper::createGrounedSettings_  (const QString &file_path)
{
    QSettings defaultSettings(file_path,QSettings::IniFormat);
    defaultSettings.setValue("Test","te");
    defaultSettings.setValue("Work","wk");
    defaultSettings.setValue("Input count","num=");
    defaultSettings.setValue("Start","sta");
    defaultSettings.setValue("Stop","sto");
    defaultSettings.setValue("Resistance","res=");
    defaultSettings.sync();
}

QStringList SettingsHelper::getDebuggerList()
{
    return groundedSettings_->allKeys();
}

QString SettingsHelper::getCmdByKey(QString cmd)
{
    qDebug() << cmd;
  return groundedSettings_->value(cmd).toString();
}

void SettingsHelper::save(const QString &key, QVariant val)
{
    settings_->setValue(key,val);
}

QVariant SettingsHelper::get(const QString &key, QVariant def)
{
    QVariant data = settings_->value(key);
    if (!data.isNull() && data.isValid()) {
        return data;
    }
    return def;
}

int SettingsHelper::getNavigationViewMode()
{
   return this->get("NavigateViewMode",QVariant(0)).toInt();
}

void SettingsHelper::saveNavigationViewMode(int mode)
{
    save("NavigateViewMode",mode);
}

int  SettingsHelper::getDarkMode()
{
  return this->get("DarkMode",QVariant(0)).toInt();
}

void SettingsHelper::saveDarkMode(int mode)
{
     save("DarkMode",mode);
}

QString SettingsHelper::getLanguage()
{
    return this->get("Language",QVariant(0)).toString();
}

void SettingsHelper::saveLanguage(const QString &language)
{
    save("Language",language);
}





